package org.jeecg.modules.weixin.service;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RestUtil;
import org.springframework.beans.factory.annotation.Value;

public class QiywxService {
    @Value("${qiywx.corpid}")
    String corpid = "ww5caf53940fa3ba60";

    @Value("${qiywx.corpsecret}")
    String corpsecret = "3DW7quNBiquqGHBHZ6vgdMENQOqY1N1XJOujjP5PE8g";

    String getAccessToken() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("corpid", corpid);
        jsonObject.put("corpsecret", corpsecret);
        jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken", jsonObject);

        return jsonObject.getString("access_token");
    }

    String getJsapiTicket(String type) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("access_token", getAccessToken());
        if(type != null && type.equals("agent_config")) {
            jsonObject.put("type", "agent_config");
            jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/ticket/get", jsonObject);

        } else
            jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket", jsonObject);

        return jsonObject.getString("ticket");
    }

    public String getSignature(String type, String noncestr, String timestamp, String url) {
        return DigestUtils.sha1Hex("jsapi_ticket=" + getJsapiTicket(type) + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url);
    }

    public String externalcontact(String externalUserid) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("access_token", getAccessToken());
        jsonObject.put("external_userid", externalUserid);
        jsonObject = RestUtil.get("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get", jsonObject);

        return jsonObject.toJSONString();
    }

}
